package com.yixing.captcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private static final long TIME_OUT = 60 * 1000;
    @RequestMapping("/check")
    public boolean check(String input, HttpSession session) {
        if(!StringUtils.hasLength(input)) {
            return false;
        }
        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveCaptchaDate = (Date)session.getAttribute(KAPTCHA_SESSION_DATE);
        if(input.equals(saveCaptcha)) {
            if(saveCaptchaDate != null && System.currentTimeMillis() - saveCaptchaDate.getTime() < TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
